<template>
  <div class="comment">
    <!-- 评论编辑部分 -->
    <van-cell-group>
      <van-field v-model="comment" label="发表评论" type="textarea" />
    </van-cell-group>
    <van-button type="primary" block @click="addComment">提交评论</van-button>

    <!-- 评论展示部分 -->
    <div class="commentList">
      <van-card v-for="(item,index) in commentList" :key="index">
        <template #thumb>
          <van-icon name="https://b.yzcdn.cn/vant/icon-demo-1126.png" />
          <div>{{item.user_name}}</div>
        </template>
        <template #title>
          <van-rate v-model="item.rate" readonly />
        </template>
        <template #desc>
          <div>{{item.content}}</div>
        </template>
        <template #price>
          <div>{{item.add_time}}</div>
        </template>
      </van-card>
      <van-loading v-if="loading" />
      <van-button type="danger" block @click="getCommentList" v-if="loadflag">加载更多</van-button>
    </div>
  </div>
</template>

<script>
import { getCommentList, addComment } from '@/api/newinfo'
export default {
  name: 'comment',

  data () {
    return {
      comment: '',
      star: 5,
      commentList: [],
      queryCom: {
        pageindex: 0,
        limit: 5
      },
      // 加载更多按钮的显示
      loadflag: true,
      // 加载时的显示
      loading: false
    }
  },
  props: ['id'],
  created () {
    // 获取所有评论列表
    this.getCommentList();
  },
  methods: {
    // 获取评论
    async getCommentList () {
      this.loading = true;
      // 先++作请求
      this.queryCom.pageindex++
      const res = await getCommentList(this.id, this.queryCom)
      // 若无数据则不显示加载更多
      if (res.data.message.length === 0) {
        this.loadflag = false
        return
      }
      // 连接
      this.commentList = this.commentList.concat(res.data.message)
      this.loading = false;
    },
    // 添加评论
    async addComment () {
      const res = await addComment(this.id, this.comment);
      console.log(res.data.message);
      this.queryCom.pageindex--;
      this.getCommentList();
      this.comment = '';
    }
  }
}
</script>

<style lang='scss'>
.comment {
  margin-bottom: 50px;
  .van-field {
    border: 1px solid #ccc;
    height: 70px;
    margin: 10px 0;
  }
  .van-field__label {
    font-weight: 600;
    font-size: 16px;
    color: black;
  }
  .van-card__thumb .van-icon {
    font-size: 50px;
  }
  .van-rate {
    margin-bottom: 15px;
  }
}
</style>